package com.xueyl.springboot.log;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoAppender extends AppenderSkeleton{
	
	private MongoClient mongoClient;
	
	private MongoDatabase mongoDatabase;
	
	private MongoCollection<BasicDBObject> logsCollection;
	
	private String connectionUrl;
	
	private String databaseName;
	
	private String collectionName;
	
	
	@Override
	public void close() {
		if(mongoClient != null){
			mongoClient.close();
		}
	}

	@Override
	public boolean requiresLayout() {
		return false;
	}

	@Override
	protected void append(LoggingEvent event) {
		if(mongoDatabase == null){
			MongoClientURI clientURI = new MongoClientURI(connectionUrl);
			mongoClient = new MongoClient(clientURI);
			mongoDatabase = mongoClient.getDatabase(databaseName);
			logsCollection = mongoDatabase.getCollection(collectionName,BasicDBObject.class);
		}
		
		logsCollection.insertOne((BasicDBObject) event.getMessage());
	}

	public void setConnectionUrl(String connectionUrl){
		this.connectionUrl = connectionUrl;
	}
	
	public void setDatabaseName(String databaseName){
		this.databaseName = databaseName;
	}
	
	public void setCollectionName(String collectionName){
		this.collectionName = collectionName;
	}
}
